import * as vscode from 'vscode';
import { DeepseekAPI } from './deepseekAPI';
import { CodebaseAnalyzer } from './codebaseAnalyzer';

export interface CodeCompletion {
    text: string;
    range: vscode.Range;
}

export interface CodeRefactoring {
    title: string;
    description: string;
    changes: {
        file: string;
        edits: {
            range: vscode.Range;
            newText: string;
            explanation?: string;
        }[];
    }[];
}

interface Suggestion {
    text: string;
    description: string;
    documentation: string;
    type: string;
    insertText?: string;
    sortText?: string;
}

interface RefactoringEdit {
    start: number;
    end: number;
    newText: string;
    explanation?: string;
}

interface RefactoringChange {
    file: string;
    edits: RefactoringEdit[];
}

interface Refactoring {
    title: string;
    description: string;
    type: string;
    priority: string;
    changes: RefactoringChange[];
}

export class CodeAssistant {
    private deepseekAPI: DeepseekAPI;
    private codebaseAnalyzer: CodebaseAnalyzer;
    private codebaseContext: any = null;
    private lastAnalysisTime: number = 0;
    private ANALYSIS_CACHE_TIME = 5 * 60 * 1000; // 5分钟缓存

    constructor(deepseekAPI: DeepseekAPI) {
        this.deepseekAPI = deepseekAPI;
        this.codebaseAnalyzer = new CodebaseAnalyzer(deepseekAPI);
    }

    private async getCodebaseContext() {
        const now = Date.now();
        if (!this.codebaseContext || (now - this.lastAnalysisTime > this.ANALYSIS_CACHE_TIME)) {
            try {
                const analysis = await this.codebaseAnalyzer.analyzeCodebase({
                    maxFiles: 50,
                    excludePatterns: [
                        'node_modules',
                        'dist',
                        '.git',
                        '*.map',
                        '*.min.*',
                        'out',
                        'build'
                    ]
                });
                this.codebaseContext = analysis;
                this.lastAnalysisTime = now;
            } catch (error) {
                console.warn('Failed to get codebase context:', error);
                return null;
            }
        }
        return this.codebaseContext;
    }

    private getCompletionItemKind(type: string): vscode.CompletionItemKind {
        switch (type.toLowerCase()) {
            case 'function':
                return vscode.CompletionItemKind.Function;
            case 'method':
                return vscode.CompletionItemKind.Method;
            case 'class':
                return vscode.CompletionItemKind.Class;
            case 'variable':
                return vscode.CompletionItemKind.Variable;
            case 'property':
                return vscode.CompletionItemKind.Property;
            default:
                return vscode.CompletionItemKind.Snippet;
        }
    }

    public async provideCompletions(
        document: vscode.TextDocument,
        position: vscode.Position,
        context: vscode.CompletionContext
    ): Promise<vscode.CompletionItem[]> {
        try {
            // 获取当前行之前的代码上下文
            const linePrefix = document.lineAt(position).text.substr(0, position.character);
            const prefixLines = 10; // 获取前10行作为上下文
            const startLine = Math.max(0, position.line - prefixLines);
            const contextRange = new vscode.Range(
                new vscode.Position(startLine, 0),
                position
            );
            const codeContext = document.getText(contextRange);

            // 获取代码库上下文
            const codebaseContext = await this.getCodebaseContext();
            
            // 根据是否有代码库上下文调用不同的API
            const response = codebaseContext 
                ? await this.deepseekAPI.getCompletionsWithCodebase(
                    codeContext, 
                    linePrefix,
                    codebaseContext,
                    document.languageId
                )
                : await this.deepseekAPI.getCompletions(codeContext, linePrefix);
            
            // 转换为 VSCode 补全项
            return response.suggestions.map((suggestion: Suggestion) => {
                const item = new vscode.CompletionItem(
                    suggestion.text,
                    this.getCompletionItemKind(suggestion.type)
                );
                item.detail = suggestion.description;
                item.documentation = new vscode.MarkdownString(suggestion.documentation);
                item.insertText = suggestion.insertText || suggestion.text;
                item.sortText = suggestion.sortText;
                return item;
            });
        } catch (error) {
            console.error('Code completion error:', error);
            return [];
        }
    }

    public async provideRefactorings(document: vscode.TextDocument): Promise<CodeRefactoring[]> {
        try {
            const code = document.getText();
            const response = await this.deepseekAPI.analyzeCode(code);
            
            // 解析并返回重构建议
            return response.refactorings.map((refactoring: Refactoring) => ({
                title: `[${refactoring.priority.toUpperCase()}] ${refactoring.title}`,
                description: `${refactoring.description}\n\n类型: ${refactoring.type}`,
                changes: refactoring.changes.map(change => ({
                    file: document.uri.fsPath,
                    edits: change.edits.map(edit => ({
                        range: new vscode.Range(
                            document.positionAt(edit.start),
                            document.positionAt(edit.end)
                        ),
                        newText: edit.newText,
                        explanation: edit.explanation
                    }))
                }))
            }));
        } catch (error) {
            console.error('Code refactoring error:', error);
            return [];
        }
    }

    public async applyRefactoring(refactoring: CodeRefactoring): Promise<void> {
        const edit = new vscode.WorkspaceEdit();
        
        for (const change of refactoring.changes) {
            const uri = vscode.Uri.file(change.file);
            for (const textEdit of change.edits) {
                edit.replace(uri, textEdit.range, textEdit.newText);
                // 添加编辑说明
                if (textEdit.explanation) {
                    edit.insert(uri, textEdit.range.end, 
                        `\n// 修改原因: ${textEdit.explanation}\n`);
                }
            }
        }

        await vscode.workspace.applyEdit(edit);
    }
} 